import { Request, Response } from 'express';
import express from "express";
import * as bodyParser from 'body-parser';
import { gms } from './gm';
import { delay } from '@/utils/MockUtils';

//配置Mock用的express.
let app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded


const sessions = [];

const proxy = {
    'post /api/v1/sessions/login': function (req: Request, res: Response) {
        res.setHeader('Access-Control-Allow-Origin', '*');

        // console.debug('post/api/v1/sessions/login req.body', req.body);

        // console.log('req.body.username',req.body.username);
        const user = req.body;
        
        if (user) {
            let gm = gms.find(item=>{
                return user.username === item.username && user.password === item.password;
            })

            sessions.push({
                'session_id': 'd6db3883894982872hsdj29sj239d92',
                'create_time': new Date().getTime(),
                'display_name': gm.username,
                'authority': gm.gm_id === 0 ? 'root' : 'gm'
            });
    
            const session = sessions[sessions.length - 1];
    
            res.json({
                'error_code': 0,
                'data': {
                    'session_id': session.session_id,
                    'create_time': session.create_time,
                    'display_name': session.display_name,
                    'authority': session.authority
                }
            }).end();
            return;
        }

        res.status(401).json({
            'error_code':-1,
            'data':'401: 用户没有权限（令牌、用户名、密码错误）。'
        })
    },

    'post /api/v1/sessions/logout/:id': function (req: Request, res: Response) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        let sessionId = req.params.id;
        // console.log('sessions',sessions);
        // console.log('sessionId',sessionId);
        
        let index = sessions.findIndex(session => {
            return session.session_id === sessionId;
        });
        if (index !== -1) {
            sessions.splice(index, 1);
            res.json({
                'error_code': 0,
                'data': {
                    'session_id': 'd6db3883894982872hsdj29sj239d92'
                }
            });
        }else{
            res.json({
                'error_code':-1,
                'data':'注销时出错!将执行强制注销',
            });
        }
    }
};

export default delay(proxy,2000);//模拟延迟
